package com.zp.resource.common;

import java.util.List;
import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.stereotype.Component;

import com.zp.domain.ContentType;
import com.zp.domain.ModuleType;
import com.zp.domain.Type;
import com.zp.framework.jpa.IJpaDao;
import com.zp.util.Constant;
import com.zp.util.Dom4JUtil;
import com.zp.util.MyException;

/**
 * common services for all the services class
 * 
 * @author chenlijun08@gmail.com
 * 
 * @version 1.0
 * 
 * @date 2014/2/12
 * 
 */
@Component
public class BaseServices {

	@Resource(name="jpaDao")
	protected IJpaDao jpaDao;

	protected Log logger = LogFactory.getLog(BaseServices.class);
	
	protected String serverPath=Dom4JUtil.parserXml(Constant.PATH_FILE_NAME).get(Constant.SERVER_PATH_KEY);

	protected JSONObject getJSONObject(String json) {
		JSONObject JO = null;
		try {
			JO = new JSONObject(json);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return JO;
	}

	protected Type getTypeByCode(String code) {
		String jpql = "from Type where code=?";
		Object[] queryParams = { code };
		Type type = null;
		try {
			List<?> list = this.jpaDao.getResultData(Constant.NEGATIVE_ONE,
					Constant.NEGATIVE_ONE, jpql, queryParams);
			if (list != null && list.size() > Constant.ZERO) {
				type = (Type) list.get(Constant.ZERO);
			}
		} catch (MyException e) {
			e.printStackTrace();
		}
		return type;
	}

	protected ContentType getContentTypeByCode(String code) {
		String jpql = "from ContentType where code=?";
		Object[] queryParams = { code };
		ContentType type = null;
		try {
			List<?> list = this.jpaDao.getResultData(Constant.NEGATIVE_ONE,
					Constant.NEGATIVE_ONE, jpql, queryParams);
			if (list != null && list.size() > Constant.ZERO) {
				type = (ContentType) list.get(Constant.ZERO);
			}
		} catch (MyException e) {
			e.printStackTrace();
		}
		return type;
	}

	protected ModuleType getModuleTypeByCode(String code) {
		String jpql = "from ModuleType where code=?";
		Object[] queryParams = { code };
		ModuleType type = null;
		try {
			List<?> list = this.jpaDao.getResultData(Constant.NEGATIVE_ONE,
					Constant.NEGATIVE_ONE, jpql, queryParams);
			if (list != null && list.size() > Constant.ZERO) {
				type = (ModuleType) list.get(Constant.ZERO);
			}
		} catch (MyException e) {
			e.printStackTrace();
		}
		return type;
	}
	
}
